package com.zhugang.week04;

import java.util.Arrays;

/**
 * @program algorithms
 * @description: smallestK
 * @author: chanzhugang
 * @create: 2022/06/30 17:24
 */
public class SmallestK {

    public static void main(String[] args) {
        SmallestK smallestK = new SmallestK();
        int[] arr = new int[]{1, 3, 5, 7, 2, 4, 6, 8};
        int[] res = smallestK.smallestK(arr, 4);
        for (int i : res) {
            System.out.println(i);
        }
    }

    /**
     * 面试题 17.14 最小K个数
     *
     * @param arr
     * @param k
     * @return
     */
    public int[] smallestK(int[] arr, int k) {
        // 数组排序，遍历前k个元素
        Arrays.sort(arr);
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = arr[i];
        }
       /* int i = 0;
        while (i < k) {
            res[i] = arr[i];
            i++;
        }*/
        return res;
    }
}